from http.server import BaseHTTPRequestHandler
from html.parser import unescape
from api.parse import *
import requests, json
class handler(BaseHTTPRequestHandler):
	def do_GET(self):
		self.send_response(415)
		self.send_header('Content-type', 'text/plain')
		self.end_headers()
		self.wfile.write('{"err": 1, "msg": "send POST request instead"}'.encode())
		return
	def do_POST(self):
		self.send_response(200)
		self.send_header('Content-type', 'text/plain')
		self.end_headers()
		if type_post(self) == "json":
			dat = parse_post(self)
			if "link" in dat:
				p = requests.get(dat["link"]).text
				f = p.find('fname') + 7
				if f < 7:
					self.wfile.write('{"err": 1, "msg": "post not exist"}'.encode())
					return
				kw = p[f : p.find('"', f)]
				fid = json.loads(requests.get(f'http://tieba.baidu.com/f/commit/share/fnameShareApi?ie=utf-8&fname={kw}').text)["data"]["fid"]
				if fid < 1:
					self.wfile.write('{"err": 1, "msg": "bar not exist"}'.encode())
					return
				tmp = f'"fid": "{fid}", "kw": "{kw}"'
				if p.find('<span class="tail-info">1楼') < 0 and p.find('<div  class="d_post_content_main d_post_content_firstfloor') < 0:
					self.wfile.write(f'{{"err": 2, "msg": "lz is missing", {tmp}}}'.encode())
					return
				s = p.find('data-field', p.find('<div class="l_post')) + 12
				u = json.loads(unescape(p[s : p.find("'", s)]))['author']
				if not "user_id" in u:
					self.wfile.write(f'{{"err": 2, "msg": "user does not exist", {tmp}}}'.encode())
					return
				if u["user_nickname"] == None:
					u["user_nickname"] = ""
				self.wfile.write(f'{{"err": 0, "un": "{u["user_name"]}", "nk": "{u["user_nickname"]}", "pt": "{u["portrait"]}", "id": "{u["user_id"]}", {tmp}}}'.encode())
			else:
				self.wfile.write('{"err": 1, "msg": "link not found"}'.encode())
		else:
			self.wfile.write('{"err": 1, "msg": "wrong request type"}'.encode())
		return
